<template>
    <span :style="`color: ${props.color};`">{{preTxt}} {{ d > 0 ? d + '天' : '' }}{{ h > 0 ? h : 0 }}小时{{ m > 0 ? m : 0 }}分{{ s > 0 ? s : 0}}秒</span>
</template>
<script lang="ts" setup>
import http from '@/request';
import dayjs from 'dayjs';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';

// 定义变量
const emit = defineEmits(['end', 'remind']);
const props = withDefaults(defineProps<{
    expireTime?: Date; // 过期时间
    preTxt?: string; // 前置文本
    remind?: number; // 提醒（单位：秒）
    color?: string; // 颜色
}>(), {
    preTxt: '',
    color: 'var(--el-color-primary)'
});

const expireTime = ref(props.expireTime); // 过期时间
const curTime = ref(new Date()); // 当前时间
const times = ref(0); // 剩余次数

// 监听属性
watch(() => props.expireTime, () => {
    expireTime.value = props.expireTime;
});

// 计算属性
const d = computed(() => !expireTime.value ? '-' : Math.floor((expireTime.value.getTime() - curTime.value.getTime()) / 1000 / 60 / 60 / 24));
const h = computed(() => !expireTime.value ? '-' : Math.floor(((expireTime.value.getTime() - curTime.value.getTime()) / 1000 / 60 / 60) % 24));
const m = computed(() => !expireTime.value ? '-' : Math.floor(((expireTime.value.getTime() - curTime.value.getTime()) / 1000 / 60 ) % 60));
const s = computed(() => !expireTime.value ? '-' : Math.floor(((expireTime.value.getTime() - curTime.value.getTime()) / 1000 ) % 60));

let timerId; // 用于存储setTimeout的ID

// 组件挂载完成后，执行如下方法
onMounted(async () => {
    synTime();
});

// 当组件卸载时清除定时器
onUnmounted(() => {
    if (timerId) {
        
        clearTimeout(timerId);
    }
});

async function synTime() {
    if (!expireTime.value) {
        timerId = setTimeout(synTime, 1000);
        return;
    }

    if (times.value <= 0) {
        times.value = 30;
        const { data: { data } } = await http.post("login/sysTime", {});
        curTime.value = dayjs(data, 'YYYY-MM-DD HH:mm:ss').toDate();
    } else {
        curTime.value = dayjs(curTime.value).add(1, 'second').toDate();
        times.value--;
    }

    if (props.remind && curTime.value.getTime() + (props.remind * 1000) >= expireTime.value.getTime()) {
        emit('remind');
    }

    if (curTime.value.getTime() >= expireTime.value.getTime()) {
        emit('end');
        return;
    }

    timerId = setTimeout(synTime, 1000);
}
</script>


<style lang="scss" scoped>
span {
    font-weight: bold;
    font-size: 14px;
    color: var(--el-color-primary);
}
</style>